package me.numark.activities;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.model.LogInResponse;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;

public class ModifyPasswdActivuty extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.right_text)
    TextView submit;

    @Bind(R.id.mobile_edit)
    EditText phoneNumber;

    @Bind(R.id.verify_code_edit)
    EditText verifyCodeEdit;

    @Bind(R.id.verify_code_button)
    TextView verifyCodeButton;

   /* @Bind(R.id.old_password_edit)
    EditText oldpasswordEdit;*/

    @Bind(R.id.password_edit)
    EditText passwordEdit;

    @Bind(R.id.password_icon)
    ImageView passwordIcon;

    User mUser;
    boolean fromLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_modify_passwd_activuty;
        super.onCreate(savedInstanceState);
        fromLogin = getIntent().getBooleanExtra("fromLogin",false);

        if (!fromLogin) {
            mUser = Global.currentUser;
            if (mUser.phone == null || mUser.phone.equals("")) {
                Utils.showToast(R.string.not_bind_cellphone);
                finish();
            }
        }
        initUI(fromLogin);
    }

    private void initUI(boolean fromLogin) {
        if (fromLogin){
            titleTextView.setText(getString(R.string.forget_password));
        }else {
            titleTextView.setText(R.string.security_setting);
            phoneNumber.setText(mUser.phone);
            phoneNumber.setEnabled(false);
            phoneNumber.setFocusable(false);
        }
        submit.setVisibility(View.VISIBLE);
        submit.setText(R.string.finish);
        verifyCodeButton.setOnClickListener(this);
        passwordIcon.setOnClickListener(this);
        submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.password_icon:
                passwordIcon.setSelected(!passwordIcon.isSelected());
                passwordEdit.setTransformationMethod(passwordIcon.isSelected() ?
                        SingleLineTransformationMethod.getInstance() :
                        PasswordTransformationMethod.getInstance());
                break;
            case R.id.verify_code_button:
                getVerifyCode();
                mHandler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
                break;
            case R.id.right_text:
                if (isInputValid()) {
                    doModify();
                }
                break;
        }

    }

    private void doModify() {
        final Map<String,Object>params = new HashMap<>();
        params.put("cellphone", phoneNumber.getText().toString());
        params.put("password", passwordEdit.getText().toString());
        params.put("code", verifyCodeEdit.getText().toString());
       // params.put("old_password", oldpasswordEdit.getText().toString());
        new RequestServerTask<LogInResponse>(LogInResponse.class, this, getString(R.string.modifying)) {
            @Override
            protected String requestServer() {
                return HttpUtil.post(NetworkConstants.CHANGE_PASSWORD_URL, params);
            }

            @Override
            protected void onSuccess(LogInResponse result) {
                if (mUser != null) {
                    Settings.delUser(Integer.toString(mUser.uid));
                }
                Intent intent = new Intent(ModifyPasswdActivuty.this,LogInActivity.class);
                startActivity(intent);
                Utils.showToast(R.string.modify_success);
                finish();
            }

        }.start();
    }

    private void getVerifyCode() {
        final Map<String,Object> params = new HashMap<>();
        params.put("cellphone", phoneNumber.getText().toString());
        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string.getting_registration_sms)) {
            @Override
            protected String requestServer() {
                return HttpUtil.get(NetworkConstants.CHANGE_PASSWORD_URL, params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                Utils.showSnackbar(rootView,R.string.get_registration_sms_success);
            }

        }.setDefaultErrMsg(R.string.get_registration_sms_failed).start();
    }

    private boolean isInputValid() {

        //String oldpassword = oldpasswordEdit.getText().toString().trim();
        /*if (oldpassword.length()<getResources().getInteger(R.integer.min_password_length)){
            return false;
        }*/

        String mobile = phoneNumber.getText().toString();
        if (mobile.length() != getResources().getInteger(R.integer.mobile_length)) {
            Utils.showToast(R.string.please_input_mobile_number);
            return false;
        }
        String verifyCode = verifyCodeEdit.getText().toString();
        if (verifyCode.length() != getResources().getInteger(R.integer.verify_code_length)) {
            Utils.showToast(R.string.invalid_verify_code);
            return false;
        }
        String password = passwordEdit.getText().toString();
        if (password.length() < getResources().getInteger(R.integer.min_password_length)) {
            Utils.showToast(R.string.password_too_short);
            return false;
        }
        return true;
    }

    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = Constants.SMS_COUNT_DOWN_TIME;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    verifyCodeButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    verifyCodeButton.setText(
                            String.format(getString(R.string.count_down_time_left), countDown));

                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        sendEmptyMessage(MSG_COUNT_DOWN_FINISHED);
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    verifyCodeButton.setText(R.string.get_verify_code);
                    verifyCodeButton
                            .setTextColor(getResources().getColor(android.R.color.white));
                    verifyCodeButton.setEnabled(true);
                    countDown = Constants.SMS_COUNT_DOWN_TIME;
                    break;

            }

        }
    };

    private void finishCountdown() {
        countDown = 0;
        mHandler.removeMessages(MSG_COUNT_DOWN);
    }

    @Override
    protected void onDestroy() {
        finishCountdown();
        super.onDestroy();
    }
}
